import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { http, API_PATH } from '../utils/http';

// 文章接口
interface ArticleTopic {
    article_id: string;
    title: string;
    content_length: number;
    created_at: number;
    uploader_id: string;
    uploader_name: string;
}

const ArticleCenter: React.FC = () => {
    const navigate = useNavigate();
    const [modalVisible, setModalVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState({
        title: '',
        content: ''
    });

    // 文章列表相关状态
    const [articles, setArticles] = useState<ArticleTopic[]>([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize] = useState(20);
    const [total, setTotal] = useState(0);
    const [listLoading, setListLoading] = useState(false);

    // Toast提示组件
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info'; visible: boolean }>({
        message: '',
        type: 'info',
        visible: false
    });

    // 显示Toast
    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        setToast({ message, type, visible: true });
        // 自动关闭
        setTimeout(() => {
            setToast(prev => ({ ...prev, visible: false }));
        }, 2000);
    };

    // 获取文章列表
    const fetchArticles = async () => {
        try {
            setListLoading(true);
            const response = await http.get<ArticleTopic>(
                API_PATH.ARTICLE_CENTER.LIST,
                { page: currentPage, page_size: pageSize }
            );

            response.onSuccess(() => {
                setArticles(response.list);
                const meta = response.meta;
                if (meta) {
                    setTotal(meta.total);
                }
            }).onError((code, msg) => {
                console.error(`获取文章列表失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`获取文章列表失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setListLoading(false);
        }
    };

    // 初始化加载文章列表
    useEffect(() => {
        fetchArticles();
    }, [currentPage]);

    // 格式化时间
    const formatTime = (timestamp: number) => {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    // 返回首页
    const handleBack = () => {
        navigate('/');
    };

    // 创建文章
    const createArticle = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!formData.title.trim() || !formData.content.trim()) {
            showToast('请输入文章标题和内容', 'info');
            return;
        }

        try {
            setLoading(true);
            const response = await http.post<ArticleTopic>(
                API_PATH.ARTICLE_CENTER.CREATE,
                formData
            );

            response.onSuccess(() => {
                // 隐藏弹窗
                setModalVisible(false);
                // 清空输入
                setFormData({ title: '', content: '' });
                // 显示成功提示
                showToast('创建文章成功', 'success');
            }).onError((code, msg) => {
                console.error(`创建失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`创建失败: ${msg}`, 'error');
            });

        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-100 bg-fixed">
            {/* 背景装饰元素 */}
            <div className="fixed inset-0 overflow-hidden pointer-events-none">
                <div className="absolute top-40 right-[10%] w-64 h-64 bg-indigo-200/20 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '0s' }}></div>
                <div className="absolute top-20 left-[5%] w-96 h-96 bg-purple-200/30 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '-2s' }}></div>
                <div className="absolute top-1/2 left-[40%] w-44 h-44 bg-green-200/30 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '-1s' }}></div>
                <div className="absolute bottom-40 right-[30%] w-72 h-72 bg-yellow-200/30 rounded-full mix-blend-multiply filter blur-2xl opacity-20 animate-floating" style={{ animationDelay: '-3s' }}></div>
            </div>

            {/* 顶部导航栏 */}
            <header className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex justify-between items-center h-16">
                        <div className="flex items-center">
                            <button
                                onClick={handleBack}
                                className="inline-flex items-center px-3.5 py-2 border border-gray-200/70 rounded-lg text-sm font-medium text-gray-700 bg-white/90 hover:bg-indigo-50/80 hover:text-indigo-600 hover:border-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-200 shadow-sm backdrop-blur-sm"
                            >
                                <svg className="w-5 h-5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                                </svg>
                                返回首页
                            </button>
                        </div>
                        <h1 className="text-xl font-semibold text-gray-900 relative">
                            <span className="relative z-10 bg-clip-text text-transparent bg-gradient-to-r from-indigo-600 to-purple-600">文章中心</span>
                            <span className="absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-indigo-200 to-purple-200 -z-0 rounded-full transform translate-y-1"></span>
                        </h1>
                        <div className="flex items-center">
                            <button
                                onClick={() => setModalVisible(true)}
                                className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all duration-200"
                            >
                                <svg className="w-5 h-5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                                </svg>
                                新增文章
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            {/* 主内容区 */}
            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8">
                    {/* 文章列表 */}
                    <div className="space-y-4">
                        {listLoading ? (
                            <div className="flex justify-center items-center py-12">
                                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-500"></div>
                            </div>
                        ) : !articles || articles.length === 0 ? (
                            <div className="text-center py-12 text-gray-500">
                                暂无文章
                            </div>
                        ) : (
                            <div className="divide-y divide-gray-100">
                                {articles.map((article) => (
                                    <div
                                        key={article.article_id}
                                        className="py-6 px-4 hover:bg-gray-50 transition-colors duration-200 cursor-pointer"
                                        onClick={() => navigate(`/article-detail/${article.article_id}`)}
                                    >
                                        <div className="flex items-center justify-between">
                                            <h3 className="text-lg font-medium text-gray-800 truncate">
                                                {article.title}
                                            </h3>
                                            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 ml-4">
                                                <svg className="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                                </svg>
                                                {article.content_length} 字
                                            </span>
                                        </div>
                                        <div className="flex items-center text-sm text-gray-500 space-x-4 mt-2">
                                            <span className="flex items-center">
                                                <svg className="w-4 h-4 mr-1.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                </svg>
                                                {article.uploader_name}
                                            </span>
                                            <span className="flex items-center">
                                                <svg className="w-4 h-4 mr-1.5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                </svg>
                                                {formatTime(article.created_at)}
                                            </span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}

                        {/* 分页 */}
                        {total > 0 && (
                            <div className="flex justify-center items-center mt-8 space-x-2">
                                <button
                                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                                    disabled={currentPage === 1}
                                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                                >
                                    <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
                                    </svg>
                                    上一页
                                </button>
                                <span className="text-sm text-gray-500">
                                    第 {currentPage} 页 / 共 {Math.ceil(total / pageSize)} 页
                                </span>
                                <button
                                    onClick={() => setCurrentPage(prev => Math.min(Math.ceil(total / pageSize), prev + 1))}
                                    disabled={currentPage >= Math.ceil(total / pageSize)}
                                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
                                >
                                    下一页
                                    <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
                                    </svg>
                                </button>
                            </div>
                        )}
                    </div>
                </div>
            </main>

            {/* 创建文章弹窗 */}
            {modalVisible && (
                <div className="fixed inset-0 bg-black/70 flex items-center justify-center p-4 z-50 animate-fadein">
                    <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl animate-scalein border border-gray-100">
                        <div className="relative">
                            {/* 头部区域 */}
                            <div className="px-6 py-5 border-b border-gray-100">
                                <h3 className="text-lg font-semibold text-gray-800 relative">
                                    <span className="relative z-10">新建文章</span>
                                    <span className="absolute inset-x-0 bottom-0 h-2 bg-indigo-100/50 -z-0 rounded-full transform -translate-y-2"></span>
                                </h3>
                                <button
                                    onClick={() => setModalVisible(false)}
                                    className="absolute top-5 right-6 text-gray-400 hover:text-gray-600 transition-colors duration-200 hover:rotate-90 transform"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            {/* 表单内容 */}
                            <div className="px-6 py-5">
                                <form onSubmit={createArticle}>
                                    <div className="mb-5">
                                        <label className="block text-gray-700 text-sm font-medium mb-2">
                                            文章标题
                                        </label>
                                        <input
                                            type="text"
                                            className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent text-gray-700 shadow-sm transition-all duration-200 bg-white box-border"
                                            placeholder="请输入文章标题"
                                            value={formData.title}
                                            onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                                        />
                                    </div>

                                    <div className="mb-5">
                                        <label className="block text-gray-700 text-sm font-medium mb-2">
                                            文章内容
                                        </label>
                                        <textarea
                                            className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none text-gray-700 shadow-sm transition-all duration-200 bg-white box-border"
                                            rows={6}
                                            placeholder="请输入文章内容"
                                            value={formData.content}
                                            onChange={(e) => setFormData(prev => ({ ...prev, content: e.target.value }))}
                                        />
                                    </div>

                                    {/* 按钮组 */}
                                    <div className="flex justify-end gap-3 pt-2">
                                        <button
                                            type="button"
                                            onClick={() => setModalVisible(false)}
                                            className="px-5 py-2.5 border border-gray-200 rounded-xl text-gray-600 hover:bg-gray-50 hover:text-gray-800 focus:outline-none focus:ring-2 focus:ring-gray-200 text-sm font-medium transition-colors duration-200 flex items-center"
                                        >
                                            <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                            取消
                                        </button>
                                        <button
                                            type="submit"
                                            disabled={loading}
                                            className="px-5 py-2.5 bg-gradient-to-r from-indigo-600 to-purple-600 text-white rounded-xl hover:from-indigo-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm font-medium transition-all duration-200 shadow-md hover:shadow-lg flex items-center"
                                        >
                                            {loading ? (
                                                <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                                </svg>
                                            ) : (
                                                <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                                                </svg>
                                            )}
                                            {loading ? '提交中...' : '创建文章'}
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Toast提示 */}
            {toast.visible && (
                <div className="fixed bottom-6 right-6 z-50 animate-scalein">
                    <div className={`rounded-xl shadow-lg py-3 px-4 flex items-center gap-2 ${toast.type === 'success' ? 'bg-emerald-500 text-white' :
                        toast.type === 'error' ? 'bg-rose-500 text-white' :
                            'bg-indigo-500 text-white'
                        } border ${toast.type === 'success' ? 'border-emerald-400' :
                            toast.type === 'error' ? 'border-rose-400' :
                                'border-indigo-400'
                        }`}>
                        {toast.type === 'success' && (
                            <svg className="w-5 h-5 drop-shadow-sm" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'error' && (
                            <svg className="w-5 h-5 drop-shadow-sm" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                            </svg>
                        )}
                        {toast.type === 'info' && (
                            <svg className="w-5 h-5 drop-shadow-sm" viewBox="0 0 20 20" fill="currentColor">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2h-1V9z" clipRule="evenodd" />
                            </svg>
                        )}
                        <span className="font-medium drop-shadow-sm">{toast.message}</span>
                    </div>
                </div>
            )}

            {/* 添加自定义动画样式 */}
            <style dangerouslySetInnerHTML={{
                __html: `
                @keyframes scalein {
                    0% {
                        opacity: 0;
                        transform: scale(0.95);
                    }
                    100% {
                        opacity: 1;
                        transform: scale(1);
                    }
                }
                
                @keyframes fadein {
                    0% {
                        opacity: 0;
                    }
                    100% {
                        opacity: 1;
                    }
                }
                
                @keyframes floating {
                    0% {
                        transform: translateY(0px);
                    }
                    50% {
                        transform: translateY(-5px);
                    }
                    100% {
                        transform: translateY(0px);
                    }
                }
                
                .animate-floating {
                    animation: floating 4s ease-in-out infinite;
                }
                
                .animate-scalein {
                    animation: scalein 0.2s ease-out;
                }
                
                .animate-fadein {
                    animation: fadein 0.2s ease-out;
                }
            `}} />
        </div>
    );
};

export default ArticleCenter; 